const { SuccessModel, ErrorModel } = require('../model/responseModel')
const { queryData } = require('../controllers/influxdb')

const handleInfluxdbRoute = (req, res) => {
  const method = req.method

  if (method === 'GET' && req.path === '/') {
    return new Promise((resolve, reject) => {
      resolve(new SuccessModel('API for InfluxDB'))
    })
  }

  if (method === 'GET' && req.path === '/api/query') {
    let query = {}
    query.start = req.query.get('start')
    query.stop = req.query.get('stop')
    query.measurement = req.query.get('measurement')
    query.field = req.query.get('field')
    query.host = req.query.get('host')

    return queryData(query)
      .then((data) => {
        return new SuccessModel(data)
      })
      .catch((error) => {
        return new ErrorModel(error)
      })
  }
}

module.exports = handleInfluxdbRoute
